/*

 * @Author: yanjikun
 * @Date: 2022-01-07 14:38:40
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-02 10:56:57
 * @Description: file content
 */
import { error } from '@/utils/log'
import { NamePath } from 'ant-design-vue/lib/form/interface'
import { nextTick, ref, unref } from 'vue'
import { FormActionType, FormConfig, useFormReturnType } from '../types/form'
export const useForm = (): useFormReturnType => {
  const formRef = ref<Nullable<FormActionType>>(null)
  const getForm = async () => {
    const form = unref(formRef)
    if (!form) {
      error('尚未获得DOM实例，请在执行DOM操作时确保DOM已呈现!')
    }
    await nextTick()
    return form as FormActionType
  }
  const register = (ele: FormActionType) => {
    formRef.value = ele
  }

  const methods: FormActionType = {
    validateFields: async (nameList?: NamePath[]) => {
      const form = await getForm()
      return form.validateFields(nameList)
    },
    validate: async (nameList?: NamePath[]) => {
      const form = await getForm()
      return form.validate(nameList)
    },
    resetFields: async () => {
      const form = await getForm()
      form.resetFields()
    },
    clearValidate: async (name: string | string[]) => {
      const form = await getForm()
      return form.clearValidate(name)
    },
    handleSubmit: async () => {
      const form = await getForm()
      return form.handleSubmit()
    },
    setFieldsValue: async (values: Recordable) => {
      const form = await getForm()
      form.setFieldsValue(values)
    },
    updateConfig: async (data: Partial<FormConfig> | Partial<FormConfig>[]) => {
      const form = await getForm()
      form.updateConfig(data)
    },
  }
  return [register, methods]
}
